package com.collect.cameroon.zhiScene.zhiWidget.zhiFilterDaily;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.view.TimePickerView;
import com.collect.cameroon.R;
import com.collect.cameroon.zhiUtils.StringUtil;
import com.collect.cameroon.zhiUtils.ZHICalendarUtil;

import org.jaaksi.pickerview.dialog.DefaultPickerDialog;
import org.jaaksi.pickerview.picker.TimePicker;
import org.jaaksi.pickerview.widget.DefaultCenterDecoration;
import org.jaaksi.pickerview.widget.PickerView;

import java.text.SimpleDateFormat;
import java.util.Date;


public class ZHIRangeDateSelect extends RelativeLayout {

    public final static String RANGE_START = "START";

    public final static String RANGE_END = "END";

    private final Context mContext;

    private final String mMainText;

    private final String mDateFormatType;

    private TextView tv_due_time_start, tv_due_time_end, tv_due_time;

    private ImageView iv_due_time_start_del, iv_due_time_end_del;

    private String mStartDate;

    private String mEndDate;

    private String mRangeType = RANGE_START;

    private TimePicker mTimePicker;

    private TimePickerView mTimePickerView;

    public boolean mOnlyShowDefaultValue = false;

    public ZHIRangeDateSelect(Context context) {
        this(context, null);
    }

    public ZHIRangeDateSelect(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ZHIRangeDateSelect(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        this.mContext = context;

        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.ZHIRangeDateSelect);
        mMainText = ta.getString(R.styleable.ZHIRangeDateSelect_mainText);
        mDateFormatType = ta.getString(R.styleable.ZHIRangeDateSelect_dateFormatType);
        ta.recycle();

        initView();
    }

    @SuppressLint("SetTextI18n")
    private void initView() {
        View mView = View.inflate(mContext, R.layout.view_range_date_select, this);

        LinearLayout ll_due_time_start = mView.findViewById(R.id.ll_due_time_start);
        LinearLayout ll_due_time_end = mView.findViewById(R.id.ll_due_time_end);

        TextView tv_due_time_des = mView.findViewById(R.id.tv_due_time_des);
        tv_due_time_des.setText(mMainText);

        tv_due_time_start = mView.findViewById(R.id.tv_due_time_start);
        tv_due_time_end = mView.findViewById(R.id.tv_due_time_end);
        tv_due_time = mView.findViewById(R.id.tv_due_time);
        iv_due_time_start_del = mView.findViewById(R.id.iv_due_time_start_del);
        iv_due_time_end_del = mView.findViewById(R.id.iv_due_time_end_del);

        ll_due_time_start.setOnClickListener(v -> showTimeDialog(RANGE_START));
        ll_due_time_end.setOnClickListener(v -> showTimeDialog(RANGE_END));

        iv_due_time_start_del.setOnClickListener(v -> {
            if (mOnlyShowDefaultValue) {
                return;
            }

            String startDate = StringUtil.safeString(tv_due_time_start.getText().toString().trim());
            if (startDate.equalsIgnoreCase(mContext.getString(R.string.start_date))) {
                showTimeDialog(RANGE_START);
            } else {
                updatePromisedDueTimeStart(true, null);
            }
        });

        iv_due_time_end_del.setOnClickListener(v -> {
            if (mOnlyShowDefaultValue) {
                return;
            }

            String startDate = StringUtil.safeString(tv_due_time_end.getText().toString().trim());
            if (startDate.equalsIgnoreCase(mContext.getString(R.string.end_date))) {
                showTimeDialog(RANGE_END);
            } else {
                updatePromisedDueTimeEnd(true, null);
            }
        });
    }

    @SuppressLint("SimpleDateFormat")
    public void initTimePicker(String onStartDateFormatYyyyMmDdHhMmSs) {
        TimePicker.OnTimeSelectListener mTimeSelectListener = (picker, date) -> {
            try {
                if (mRangeType.equalsIgnoreCase(RANGE_START)) {
                    updatePromisedDueTimeStart(false, date);
                } else {
                    updatePromisedDueTimeEnd(false, date);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        };

        Date gDate = new Date();
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (TextUtils.isEmpty(onStartDateFormatYyyyMmDdHhMmSs)) {
                gDate = simpleDateFormat.parse("2019-01-01 00:00:00");
            } else {
                gDate = simpleDateFormat.parse(onStartDateFormatYyyyMmDdHhMmSs);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        long curYearTimeMils = gDate.getTime();
        long nextYearTimeMils = curYearTimeMils + 31557600000L * 10;

        PickerView.sOutTextSize = 16;
        PickerView.sCenterTextSize = 18;
        PickerView.sCenterColor = mContext.getResources().getColor(R.color.theme_color_0);
        PickerView.sOutColor = Color.GRAY;

        DefaultCenterDecoration.sDefaultLineWidth = 1;
        DefaultCenterDecoration.sDefaultLineColor = mContext.getResources().getColor(R.color.theme_color_0);

        int dtype = TimePicker.TYPE_ALL;//(TimePicker.TYPE_MIXED_DATE | TimePicker.TYPE_HOUR | TimePicker.TYPE_MINUTE);
        if (mDateFormatType.equalsIgnoreCase(ZHIRangeDateSelectClickListener.TYPE_DATE)) {
            dtype = TimePicker.TYPE_DATE;
        }

        mTimePicker = new TimePicker.Builder(mContext, dtype, mTimeSelectListener)
                .setRangDate(curYearTimeMils, nextYearTimeMils)
                .setInterceptor((pickerView, params) -> {
                    pickerView.setVisibleItemCount(5);

                    int gtype = (int) pickerView.getTag();
                    if (gtype == TimePicker.TYPE_MIXED_DATE ||
                            gtype == TimePicker.TYPE_HOUR ||
                            gtype == TimePicker.TYPE_MINUTE) {
                        pickerView.setIsCirculation(true);
                    }
                })
                .setFormatter(new TimePicker.DefaultFormatter() {
                    @Override
                    public CharSequence format(TimePicker picker, int type, int position, long num) {
                        if (type == TimePicker.TYPE_MIXED_DATE) {
                            return ZHICalendarUtil.getDateFormated(num);
                        } else if (type == TimePicker.TYPE_YEAR) {
                            return num + "";
                        } else if (type == TimePicker.TYPE_MONTH) {
                            return num + "";
                        } else if (type == TimePicker.TYPE_DAY) {
                            return num + "";
                        } else if (type == TimePicker.TYPE_HOUR) {
                            return num + "h";
                        } else if (type == TimePicker.TYPE_MINUTE) {
                            return num + "min";
                        }
                        return super.format(picker, type, position, num);
                    }
                })
                .create();

        DefaultPickerDialog dialog = (DefaultPickerDialog) mTimePicker.dialog();
        dialog.getTitleView().setText(mContext.getString(R.string.pls_select));

        TextView btnCancel = (TextView) dialog.getBtnCancel();
        btnCancel.setText(mContext.getString(R.string.cancel));
        btnCancel.setVisibility(GONE);

        TextView btnConfirm = (TextView) dialog.getBtnConfirm();
        btnConfirm.setText(mContext.getString(R.string.confirm));
    }

    public void updatePromisedDueTimeStart(boolean reset, Date date) {
        try {
            if (reset) {
                mStartDate = "";

                tv_due_time_start.setTextColor(mContext.getResources().getColor(R.color.theme_transparent_7));
                tv_due_time_start.setText(mContext.getString(R.string.start_date));
                iv_due_time_start_del.setImageResource(R.drawable.ic_125);

                String endDate = StringUtil.safeString(tv_due_time_end.getText().toString().trim());
                tv_due_time.setText(endDate.equalsIgnoreCase(mContext.getString(R.string.end_date)) ? "" : endDate);

                return;
            }

            if (date == null) {
                return;
            }

            String dateFormat;
            if (mDateFormatType.equalsIgnoreCase(ZHIRangeDateSelectClickListener.TYPE_DATE)) {
                dateFormat = ZHICalendarUtil.getDateFormated(date.getTime());
            } else {
                dateFormat = ZHICalendarUtil.getDateTimeFormated(date.getTime());
            }
            mStartDate = dateFormat;

            String showDateFormat = dateFormat;
            String[] splits = dateFormat.split(" ");
            if (splits.length > 1) {
                showDateFormat = splits[0] + "\n" + splits[1];
            }

            tv_due_time_start.setText(showDateFormat);
            tv_due_time_start.setTextColor(mContext.getResources().getColor(R.color.theme_color_0));
            iv_due_time_start_del.setImageResource(R.drawable.ic_124);

            String endDate = StringUtil.safeString(tv_due_time_end.getText().toString().trim());
            tv_due_time.setText(endDate.equalsIgnoreCase(mContext.getString(R.string.end_date)) ? dateFormat : (dateFormat + "-" + endDate));


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updatePromisedDueTimeEnd(boolean reset, Date date) {
        try {
            if (reset) {
                mEndDate = "";

                tv_due_time_end.setTextColor(mContext.getResources().getColor(R.color.theme_transparent_7));
                tv_due_time_end.setText(mContext.getString(R.string.end_date));
                iv_due_time_end_del.setImageResource(R.drawable.ic_125);

                String startDate = StringUtil.safeString(tv_due_time_start.getText().toString().trim());
                tv_due_time.setText(startDate.equalsIgnoreCase(mContext.getString(R.string.start_date)) ? "" : startDate);

                return;
            }

            if (date == null) {
                return;
            }

            String dateFormat;
            if (mDateFormatType.equalsIgnoreCase(ZHIRangeDateSelectClickListener.TYPE_DATE)) {
                dateFormat = ZHICalendarUtil.getDateFormated(date.getTime());
            } else {
                dateFormat = ZHICalendarUtil.getDateTimeFormated(date.getTime());
            }
            mEndDate = dateFormat;

            String showDateFormat = dateFormat;
            String[] splits = dateFormat.split(" ");
            if (splits.length > 1) {
                showDateFormat = splits[0] + "\n" + splits[1];
            }

            tv_due_time_end.setText(showDateFormat);
            tv_due_time_end.setTextColor(mContext.getResources().getColor(R.color.theme_color_0));
            iv_due_time_end_del.setImageResource(R.drawable.ic_124);

            String startDate = StringUtil.safeString(tv_due_time_start.getText().toString().trim());
            tv_due_time.setText(startDate.equalsIgnoreCase(mContext.getString(R.string.start_date)) ? dateFormat : (startDate + "-" + dateFormat));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void showTimeDialog(String rangeType) {
        try {
            if (mOnlyShowDefaultValue) {
                return;
            }

            mRangeType = rangeType;

            if (mTimePicker == null) {
                initTimePicker(null);
            }

            //mTimePicker.setSelectedDate(1549349843000L);
            mTimePicker.show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void reset() {
        updatePromisedDueTimeStart(true, null);
        updatePromisedDueTimeEnd(true, null);
    }

    public String getStartDate() {
        return StringUtil.safeString(mStartDate);
    }

    public String getEndDate() {
        return StringUtil.safeString(mEndDate);
    }
}
